/*
 * EmployeePositionsEditor.java
 *
 * Created on November 19, 2006, 4:42 PM
 */

package org.foment.gem.beans;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import static org.foment.joliage3.core.internationalization.Internationalization.i18n;
import org.foment.joliage3.sql.Database;
import org.omg.CORBA.DATA_CONVERSION;
import org.foment.data.User;
import org.foment.gem.Integrator;

/**
 *
 * @author  jaksa
 */
public class EmployeeCoursesEditor extends javax.swing.JPanel implements java.io.Serializable, User.UserListener {
    
    /** Creates new form BeanForm */
    public EmployeeCoursesEditor() {
        
        initComponents();
        setComponents();

        Integrator._user.addListener(this);
        checkPrivileges();
    }

  public void userLoggedIn() {

      checkPrivileges();
  }

  /* see if user has all privileges or disable all elements */
  private void checkPrivileges() {

      // if user doesn't have all access disable all fields
      java.util.LinkedList<java.awt.Container> containers = new java.util.LinkedList();
      containers.add(this);

      while(!containers.isEmpty()) {

         java.awt.Container current = containers.getFirst(); // get first element from list
         containers.removeFirst();                           // now remove it from list, it is not needed anymore

         for (java.awt.Component component: current.getComponents()) {

             if (!Integrator._user.getPrivAllAccess())
                 component.setEnabled(false);
             else
                 component.setEnabled(true);
         }

      }

  }

    private void setComponents()
    {
        comboDepartment.setQuery("SELECT departmentID as keyName, departmentTitle as fieldName from department");
        comboDepartment.listenTables("department");

        comboScienceDomain.setQuery("SELECT sd.scienceDomainID AS keyName, sd.scienceDomainTitle AS fieldName FROM scienceDomain sd " +
                " WHERE sd.scienceDomainID IN (SELECT scienceDomainID FROM scienceDomainCourses WHERE departmentID = " + comboDepartment.getValue() + " ) ; ");
        comboScienceDomain.listenTables("scienceDomain, sciencedomaincourses");

        comboCourse.setQuery("SELECT courseID as keyName, courseTitle as fieldName FROM course WHERE " +
                " courseID IN ( SELECT courseID FROM scienceDomainCourses WHERE departmentID = " + comboDepartment.getValue() +
                " AND scienceDomainID = " + comboScienceDomain.getValue() + " ) ; ");
        comboCourse.listenTables("course, sciencedomaincourses");
    }
    
    public void update() throws SQLException
    {
        lblEmployee.setText(
        "<html>(" + Database.getTable("Employee").getResultSet().getString("EmployeeID") + ") " +
        "<b>" + Database.getTable("Employee").getResultSet().getString("EmployeeSurname") + ", " +
        Database.getTable("Employee").getResultSet().getString("EmployeeFirstName") + "</b>"
        );
        
        _currentEmployee = Database.getTable("Employee").getResultSet().getInt("EmployeeID");
 
        String query = "SELECT c.courseID AS keyName, c.courseTitle AS fieldName from course c, " +
                "EmployeeCourse ec WHERE ec.EmployeeID = " + _currentEmployee + " AND ec.courseID = c.courseID;";
        
        listCurrentCourses.setQuery(query);
        listCurrentCourses.listenTables("course, EmployeeCourse");
        
        btnDeleteCourse.setEnabled(false);
        btnModifyCourse.setEnabled(false);

    }
    
    private String formatDate(int value, String pattern)
    {
        java.text.DecimalFormat df = new java.text.DecimalFormat(pattern);
        return df.format((double) value);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlEmployee = new javax.swing.JPanel();
        lblEmployee = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listCurrentCourses = new org.foment.joliage3.newt.SQLListBox();
        lblDepartment = new javax.swing.JLabel();
        lblScienceDomain = new javax.swing.JLabel();
        comboDepartment = new org.foment.joliage3.newt.SQLComboBox();
        comboScienceDomain = new org.foment.joliage3.newt.SQLComboBox();
        btnModifyCourse = new javax.swing.JButton();
        btnNewCourse = new javax.swing.JButton();
        btnDeleteCourse = new javax.swing.JButton();
        lblCourse = new javax.swing.JLabel();
        comboCourse = new org.foment.joliage3.newt.SQLComboBox();

        lblEmployee.setFont(new java.awt.Font("Dialog", 0, 12));
        lblEmployee.setText(".");

        org.jdesktop.layout.GroupLayout pnlEmployeeLayout = new org.jdesktop.layout.GroupLayout(pnlEmployee);
        pnlEmployee.setLayout(pnlEmployeeLayout);
        pnlEmployeeLayout.setHorizontalGroup(
            pnlEmployeeLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlEmployeeLayout.createSequentialGroup()
                .addContainerGap()
                .add(lblEmployee, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 737, Short.MAX_VALUE)
                .addContainerGap())
        );
        pnlEmployeeLayout.setVerticalGroup(
            pnlEmployeeLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlEmployeeLayout.createSequentialGroup()
                .addContainerGap()
                .add(lblEmployee)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        listCurrentCourses.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listCurrentCoursesValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listCurrentCourses);

        lblDepartment.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblDepartment.setText("Katedra");

        lblScienceDomain.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblScienceDomain.setText("Naučna oblast");

        comboDepartment.setFieldName("JobTitle");
        comboDepartment.setKeyName("JobID");
        comboDepartment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboDepartmentActionPerformed(evt);
            }
        });

        comboScienceDomain.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboScienceDomainActionPerformed(evt);
            }
        });

        btnModifyCourse.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_update.png"))); // NOI18N
        btnModifyCourse.setText("Izmeni predmet");

        btnNewCourse.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_insert.png"))); // NOI18N
        btnNewCourse.setText("Dodaj predmet");
        btnNewCourse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewCourseActionPerformed(evt);
            }
        });

        btnDeleteCourse.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/foment/gem/images/employees_button_reset.png"))); // NOI18N
        btnDeleteCourse.setText("Obriši predmet");
        btnDeleteCourse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteCourseActionPerformed(evt);
            }
        });

        lblCourse.setText("Predmet");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlEmployee, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 191, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(20, 20, 20)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(lblScienceDomain)
                                    .add(lblDepartment)))
                            .add(layout.createSequentialGroup()
                                .add(30, 30, 30)
                                .add(lblCourse, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 50, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(comboCourse, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE)
                            .add(comboDepartment, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE)
                            .add(comboScienceDomain, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE)))
                    .add(layout.createSequentialGroup()
                        .add(btnNewCourse, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 183, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnModifyCourse, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 190, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnDeleteCourse, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 181, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .add(181, 181, 181))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(pnlEmployee, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(lblDepartment)
                            .add(comboDepartment, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(comboScienceDomain, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(lblScienceDomain))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(comboCourse, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(lblCourse))))
                .add(26, 26, 26)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnNewCourse)
                    .add(btnModifyCourse)
                    .add(btnDeleteCourse))
                .addContainerGap(310, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void comboDepartmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboDepartmentActionPerformed
        // TODO add your handling code here:
        comboScienceDomain.setQuery("SELECT sd.scienceDomainID AS keyName, sd.scienceDomainTitle AS fieldName FROM scienceDomain sd " +
                " WHERE sd.scienceDomainID IN (SELECT scienceDomainID FROM scienceDomainCourses WHERE departmentID = " + comboDepartment.getValue() + " ) ; " );
        comboCourse.setQuery("SELECT courseID as keyName, courseTitle as fieldName FROM course WHERE " +
                " courseID IN ( SELECT courseID FROM scienceDomainCourses WHERE departmentID = " + comboDepartment.getValue() +
                " AND scienceDomainID = " + comboScienceDomain.getValue() + " ) ; " );
    }//GEN-LAST:event_comboDepartmentActionPerformed

    private void comboScienceDomainActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboScienceDomainActionPerformed
        // TODO add your handling code here:
        comboCourse.setQuery("SELECT courseID as keyName, courseTitle as fieldName FROM course WHERE " +
                " courseID IN ( SELECT courseID FROM scienceDomainCourses WHERE departmentID = " + comboDepartment.getValue() +
                " AND scienceDomainID = " + comboScienceDomain.getValue() + " ) ; " );
    }//GEN-LAST:event_comboScienceDomainActionPerformed

    private void btnNewCourseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewCourseActionPerformed
        // TODO add your handling code here:
        String query = "INSERT INTO EmployeeCourse VALUES ( '" + _currentEmployee + "' , '" + comboCourse.getValue() +
                "' ) ;";
        try
        {
            Connection  conn = Database.getConnection();
            conn.createStatement().executeUpdate(query);
            conn.close();
            Database.getTable("EmployeeCourse").reload();
        } catch (SQLException ex) {
            Logger.getLogger(EmployeeCoursesEditor.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        //listCurrentCourses.refresh();
    }//GEN-LAST:event_btnNewCourseActionPerformed

    private void btnDeleteCourseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteCourseActionPerformed
        // TODO add your handling code here:
        int position = listCurrentCourses.getValue();
        if (position != -1 && _currentEmployee != -1)
        {
            String message = "Da li ste sigurni da želite da uklonite predmet?";
            String options[] = {"Da", "Ne"};
            int option = JOptionPane.showOptionDialog(this, message, "Foment Group", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, 0);
            if (option == jOptionPane.YES_OPTION)
            {
                String query = "DELETE FROM EmployeeCourse WHERE courseID = '" + listCurrentCourses.getValue() + "' AND " +
                    "EmployeeID = '" + _currentEmployee + "' ;";
                try
                {
                    Connection  conn = Database.getConnection();
                    conn.createStatement().executeUpdate(query);
                    conn.close();
                    Database.getTable("EmployeeCourse").reload();
                } catch (SQLException ex) {
                    Logger.getLogger(EmployeeCoursesEditor.class.getName()).log(Level.SEVERE, null, ex);
                }
                //listCurrentCourses.refresh();
            }
        }
    }//GEN-LAST:event_btnDeleteCourseActionPerformed

    private void listCurrentCoursesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listCurrentCoursesValueChanged
        // TODO add your handling code here:
        btnDeleteCourse.setEnabled(true);
        //btnModifyCourse.setEnabled(true);

        listCurrentCourses.listener();
        int position = listCurrentCourses.getValue();
        if (_currentEmployee != -1 && position != -1)
        {
            int dep = -1;
            int sci = -1;
            String query = "SELECT departmentID, sciencedomainID FROM sciencedomaincourses WHERE " +
                    " courseID = '" + position + "' ;";
            try
            {
                Connection  conn = Database.getConnection();
                ResultSet rs = conn.createStatement().executeQuery(query);
                if (rs.first())
                {
                    dep = rs.getInt("departmentID");
                    sci = rs.getInt("scienceDomainID");
                    comboDepartment.setValue(dep);
                    comboScienceDomain.setValue(sci);
                    comboCourse.setValue(position);
                }
                
                rs.close();
                conn.close();
            }
            catch (SQLException ex) {
            Logger.getLogger(EmployeeCoursesEditor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_listCurrentCoursesValueChanged
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDeleteCourse;
    private javax.swing.JButton btnModifyCourse;
    private javax.swing.JButton btnNewCourse;
    private org.foment.joliage3.newt.SQLComboBox comboCourse;
    private org.foment.joliage3.newt.SQLComboBox comboDepartment;
    private org.foment.joliage3.newt.SQLComboBox comboScienceDomain;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCourse;
    private javax.swing.JLabel lblDepartment;
    private javax.swing.JLabel lblEmployee;
    private javax.swing.JLabel lblScienceDomain;
    private org.foment.joliage3.newt.SQLListBox listCurrentCourses;
    private javax.swing.JPanel pnlEmployee;
    // End of variables declaration//GEN-END:variables
 
    private int _currentEmployee  = -1;
    private JOptionPane jOptionPane;
    private String departmentQuery = "";
    private String scienceDomainQuery = "";
    private String courseQuery = "";
    
}
